package com.sharemarking.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.system.dto.Page;
import com.sharemarking.system.dto.orgManagement.OrgVerifyInfoDto;
import com.sharemarking.system.dto.orgVerify.OrgVerifyListDto;
import com.sharemarking.system.mapper.OrgMapper;
import com.sharemarking.system.mapper.OrgVerifyMapper;
import com.sharemarking.wa.common.entity.Member;
import com.sharemarking.wa.common.entity.Org;
import com.sharemarking.wa.common.entity.OrgVerify;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author dxy
 */
@Controller
@RequestMapping("system/transportManagement")
public class TransportManagementController {
    @Autowired
    private OrgVerifyMapper om;
    @Autowired
    private HttpSession session;
    @Autowired
    private OrgMapper orgMapper;

    /**
     * 列表页面
     */
    @GetMapping("index")
    @PreAuthorize("hasPermission('base','all')")
    public String index(OrgVerifyListDto obj, Integer page, Model model, Integer isSession) {
        int size = 10;
        if (page == null) {
            page = 0;
        }
        // session 参数回显
        if (isSession != null) {
            // 如果isSession为1，代表要从session取条件参数，一般应用在某操作之后要保存查询参数
            obj = session.getAttribute("query") == null ? obj : (OrgVerifyListDto) session.getAttribute("query");
            size = session.getAttribute("size") == null ? size : (int) session.getAttribute("size");
            page = session.getAttribute("page") == null ? page : (int) session.getAttribute("page");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", page * size);
        map.put("pageSize", size);
        map.put("verify", 1);
        if (!StringUtils.isEmpty(obj.getMobile())) {
            map.put("mobile", obj.getMobile());
        }
        if (!StringUtils.isEmpty(obj.getOrgName())) {
            map.put("orgName", obj.getOrgName());
        }
        List<OrgVerifyListDto> list = om.getTransportOrgList(map);
        int total = om.getTransportOrgListTotal(map);
        model.addAttribute("page", new Page<>(page, size, total, list));
        model.addAttribute("query", obj);
        // session 参数保存
        session.setAttribute("query", obj);
        session.setAttribute("size", size);
        session.setAttribute("page", page);
        return "orgManagement/transportIndex";
    }


    /**
     * 新增、编辑页面
     */
    @GetMapping("{id}")
    @PreAuthorize("hasPermission('base','all')")
    public String get(@PathVariable("id") int id, Model model) {
        OrgVerifyInfoDto obj = new OrgVerifyInfoDto();
        if (id > 0) {
            obj = om.getTransportOrgInfo(id);
        } else {
            model.addAttribute("obj", obj);
        }
        List<String> attach = om.getAttachList(id);
        model.addAttribute("attach", attach);
        model.addAttribute("obj", obj);
        return "orgManagement/transportForm";
    }

    /**
     * 新增、编辑
     *
     * @param obj
     * @param model
     * @return
     */
    @PostMapping("{id}")
    @PreAuthorize("hasPermission('base','all')")
    @Transactional
    public String post(OrgVerifyInfoDto obj, Model model, RedirectAttributes redirectAttributes) throws Exception {

        //更新用户表
        Member member = new Member();
        member.setMobile(obj.getMobile());
        member.setRealName(obj.getMemberName());
        member.setNickName("手机尾号" + member.getMobile().substring(member.getMobile().length() - 4));
        member.setHeadImg("headImg/memberBigHead.png");

        //更新企业表
        Org org = new Org();
        org.setName(obj.getName());
        org.setRealName(obj.getName());
        org.setType(2);
        if (obj.getId() == 0) {
            if (om.isBindMobile(obj.getMobile()) != 0) {
                redirectAttributes.addFlashAttribute("msg", "该手机号已经绑定其它单位！");
                return "redirect:" + obj.getId();
            }


            //插入用户
            member.setRole(4);//运输单位端
            member.setCreateDate(new Date());
            member.setPassword("96e79218965eb72c92a549dd5a330112");//默认密码111111
            member.setAlias(UUID.randomUUID().toString().replaceAll("-", ""));
            om.insertMember(member);

            //新插入企业
            org.setCreateDate(new Date());
            org.setMemberId(member.getId());
            om.insertOrg(org);


            om.insertOrgMember(org.getId(), member.getId());
        } else {
            Integer memberId = orgMapper.selectOne(new QueryWrapper<Org>().select("member_id").eq("id", obj.getId())).getMemberId();
            if (om.isBindMobileByMemberId(obj.getMobile(), memberId) != 1) {
                if (om.isBindMobile(obj.getMobile()) != 0) {
                    redirectAttributes.addFlashAttribute("msg", "该手机号已经绑定其它单位！");
                    return "redirect:" + obj.getId();
                }
            }

            //更新企业表
            org.setId(obj.getOrgId());
            om.updateOrg(org);

            //更新用户表
            member.setId(memberId);
            member.setUpdateDate(new Date());
            om.updateMember(member);
        }
        model.addAttribute("obj", obj);
        redirectAttributes.addFlashAttribute("msg", "操作成功!");
        return "redirect:index?isSession=1";
    }


    /**
     * 详情页面
     */
    @GetMapping("info/{id}")
    @PreAuthorize("hasPermission('base','all')")
    public String getInfo(@PathVariable("id") int id, Model model) {
        OrgVerify obj = new OrgVerify();
        if (id > 0) {
            obj = om.selectById(id);
        } else {
            model.addAttribute("obj", obj);
        }
        List<String> attach = om.getAttachList(id);
        model.addAttribute("attach", attach);
        model.addAttribute("obj", obj);
        return "orgVerify/info";
    }

    /**
     * 审核
     */
    @GetMapping("exam")
    @PreAuthorize("hasPermission('base','all')")
    @Transactional
    public String exam(int id, int type, String rejectReason, Model model, RedirectAttributes redirectAttributes) {
        OrgVerify orgVerify = new OrgVerify();
        orgVerify.setExamState(type);
        if (type == 2) {
            if (StringUtils.isEmpty(rejectReason)) {
                redirectAttributes.addFlashAttribute("msg", "驳回理由不可为空！");
                return "redirect:index?isSession=1";
            }
            orgVerify.setRejectReason(rejectReason);
        } else {
            orgVerify.setRejectReason(null);
        }
        orgVerify.setId(id);
        orgVerify.setUpdateDate(new Date());
        om.updateById(orgVerify);
        redirectAttributes.addFlashAttribute("msg", "操作成功！");
        return "redirect:index?isSession=1";
    }
}
